package com.iot.manage.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.iot.manage.pojo.DeviceModel;
import com.iot.manage.pojo.ModelArgs;
import com.iot.manage.result.Code;
import com.iot.manage.result.Result;
import com.iot.manage.service.DeviceModelService;
import com.iot.manage.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 设备模型管理控制层
 *
 * @author zhuzhi
 */
@RestController
@RequestMapping("/api/private/v1")
public class DeviceModelController {

    @Autowired
    private TokenService tokenService;

    @Autowired
    private DeviceModelService deviceModelService;

    /**
     * 查询设备模型信息列表
     *
     * @param token
     * @param query 模糊查询关键字
     * @param pagenum 当前页
     * @param pagesize 每页条数
     * @return
     */
    @GetMapping("/findDeviceModelList")
    public Result findDeviceModelList(
            @RequestHeader("token") String token,
            @RequestParam("query") String query,
            @RequestParam("pagenum") int pagenum,
            @RequestParam("pagesize") int pagesize) {
        Result result = new Result();
        if (!tokenService.validate(token)) {
            return result.build(null,Code.D404);
        }
        List<DeviceModel> deviceModelList;
        int deviceModelTotal;
        try{
            deviceModelList = deviceModelService.findDeviceModelList(query,pagenum,pagesize);
            deviceModelTotal = deviceModelService.countDeviceModelList(query);
        } catch (Exception e){
            e.printStackTrace();
            return result.build(null,Code.D400);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("total",deviceModelTotal);
        map.put("pagenum",pagenum);
        map.put("deviceModelList",deviceModelList);
        return result.build(map, Code.S200);
    }

    /**
     * 新增设备模型信息
     *
     * @param token
     * @param params 设备模型信息参数
     * @return
     */
    @PostMapping("/addDeviceModel")
    public Result addDeviceModel(
            @RequestHeader("token") String token,
            @RequestBody JSONObject params) {
        Result result = new Result();
        if (!tokenService.validate(token)) {
            return result.build(null,Code.D404);
        }
        try {
            if(null != findDeviceModelByIdOrCode(token,params.getString("modelCode")).getData()){
                return result.build(null, Code.D411);
            }
            params.put("modelId", UUID.randomUUID().toString().replace("-", ""));
            deviceModelService.addDeviceModel(params);
        } catch (Exception e) {
            e.printStackTrace();
            return result.build(null,Code.D400);
        }
        return result.build(null, Code.S200);
    }

    /**
     * 根据设备模型ID或设备模型标识查询设备模型信息
     *
     * @param token
     * @param params 设备模型ID或设备模型标识
     * @return
     */
    @GetMapping("/findDeviceModelByIdOrCode/{params}")
    public Result findDeviceModelByIdOrCode(
            @RequestHeader("token") String token,
            @PathVariable("params") String params){
        Result result = new Result();
        if (!tokenService.validate(token)) {
            return result.build(null,Code.D404);
        }
        DeviceModel deviceModel;
        try{
            deviceModel = deviceModelService.findDeviceModelByIdOrCode(params);
        } catch (Exception e){
            e.printStackTrace();
            return result.build(null,Code.D400);
        }
        return result.build(deviceModel, Code.S200);
    }

    /**
     * 修改设备模型信息
     *
     * @param token
     * @param params 设备模型信息参数
     * @return
     */
    @PutMapping("/updateDeviceModelInfo/{oldDeviceModelCode}")
    public Result updateDeviceModelInfo(
            @RequestHeader("token") String token,
            @PathVariable("oldDeviceModelCode") String oldDeviceModelCode,
            @RequestBody JSONObject params){
        Result result = new Result();
        if (!tokenService.validate(token)) {
            return result.build(null,Code.D404);
        }
        try {
            if (!(oldDeviceModelCode.equals(params.get("modelCode")))){
                if(null != findDeviceModelByIdOrCode(token,params.getString("modelCode")).getData()){
                    return result.build(null, Code.D411);
                }
            }
            deviceModelService.updateDeviceModelInfo(params);
        } catch (Exception e){
            e.printStackTrace();
            return result.build(null,Code.D400);
        }
        return result.build(null, Code.S200);
    }

    /**
     *删除设备模型信息
     *
     * @param token
     * @param modelId 设备模型ID
     * @return
     */
    @DeleteMapping("/deleteDeviceModelById/{modelId}")
    public Result deleteDeviceModelById(
            @RequestHeader("token") String token,
            @PathVariable("modelId") String modelId) {
        Result result = new Result();
        if (!tokenService.validate(token)) {
            return result.build(null,Code.D404);
        }
        try {
            deviceModelService.deleteDeviceModelById(modelId);
        } catch (Exception e) {
            e.printStackTrace();
            return result.build(null,Code.D400);
        }
        return result.build(null, Code.S200);
    }

    /**
     * 查询全部设备模型
     *
     * @param token
     * @return
     */
    @GetMapping("/findNotSetModelArg/{modelId}")
    public Result findNotSetModelArg(
            @RequestHeader("token") String token,
            @PathVariable("modelId") String modelId) {
        Result result = new Result();
        if (!tokenService.validate(token)) {
            return result.build(null,Code.D404);
        }
        JSONArray ja = new JSONArray();
        JSONObject jo = new JSONObject();
        List<ModelArgs> propertyList = null;
        List<ModelArgs> eventList = null;
        List<ModelArgs> serviceList = null;
        String modelArgs;
        try {
            modelArgs = deviceModelService.findModelArgById(modelId);
            String propertyParams = "";
            String eventParams = "";
            String serviceParams = "";
            if (null != modelArgs) {
                jo = jo.parseObject(modelArgs);

                String property_list = jo.getString("property_list");
                String event_list = jo.getString("event_list");
                String service_list = jo.getString("service_list");

                propertyParams = property_list.substring(1,property_list.length() - 1).replaceAll("\"","'");
                eventParams = event_list.substring(1,event_list.length() - 1).replaceAll("\"","'");
                serviceParams = service_list.substring(1,service_list.length() - 1).replaceAll("\"","'");
            }

            propertyList = deviceModelService.findPropertyArgsList(propertyParams);
            eventList = deviceModelService.findEventArgsList(eventParams);
            serviceList = deviceModelService.findServiceArgsList(serviceParams);

            Map<String,Object> map = new HashMap();
            map.put("属性",propertyList);
            map.put("事件",eventList);
            map.put("服务",serviceList);
            int initId = 1;
            for (String s : map.keySet()) {
                JSONObject joTemp = new JSONObject();
                joTemp.put("id",initId++);
                joTemp.put("pid",0);
                joTemp.put("label",s);
                joTemp.put("children",map.get(s));
                ja.add(joTemp);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return result.build(null,Code.D400);
        }
        return result.build(ja, Code.S200);
    }

    /**
     * 根据模型ID查询已设置的模型参数
     *
     * @param token
     * @param modelId 模型ID
     * @return
     */
    @GetMapping("/findModelArgById/{modelId}")
    public Result findModelArgById(
            @RequestHeader("token") String token,
            @PathVariable("modelId") String modelId) {
        Result result = new Result();
        if (!tokenService.validate(token)) {
            return result.build(null,Code.D404);
        }
        String modelArgs;
        JSONObject jo = new JSONObject();
        List<ModelArgs> propertyList = null;
        List<ModelArgs> eventList = null;
        List<ModelArgs> serviceList = null;
        JSONArray ja = new JSONArray();
        try {
            modelArgs = deviceModelService.findModelArgById(modelId);
            String propertyParams = "";
            String eventParams = "";
            String serviceParams = "";
            if (null != modelArgs){
                jo = jo.parseObject(modelArgs);
                String property_list = jo.getString("property_list");
                String event_list = jo.getString("event_list");
                String service_list = jo.getString("service_list");

                propertyParams = property_list.substring(1,property_list.length() - 1).replaceAll("\"","'");
                eventParams = event_list.substring(1,event_list.length() - 1).replaceAll("\"","'");
                serviceParams = service_list.substring(1,service_list.length() - 1).replaceAll("\"","'");
            }

            if (propertyParams.length() > 0)
            propertyList = deviceModelService.findPropertyArgsListYes(propertyParams);
            if (eventParams.length() > 0)
            eventList = deviceModelService.findEventArgsListYes(eventParams);
            if (serviceParams.length() > 0)
            serviceList = deviceModelService.findServiceArgsListYes(serviceParams);

            Map<String,Object> map = new HashMap();
            map.put("属性",propertyList);
            map.put("事件",eventList);
            map.put("服务",serviceList);
            int initId = 1;
            for (String s : map.keySet()) {
                JSONObject joTemp = new JSONObject();
                joTemp.put("id",initId++);
                joTemp.put("pid",0);
                joTemp.put("label",s);
                joTemp.put("children",null != map.get(s) ? map.get(s) : new ArrayList<>());
                ja.add(joTemp);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return result.build(null,Code.D400);
        }
        return result.build(ja, Code.S200);
    }

    /**
     * 保存分配的设备模型
     *
     * @param token
     * @param params 分配的设备模型信息
     * @return
     */
    @PostMapping("/saveDeviceModelArg")
    public Result saveDeviceModelArg(
            @RequestHeader("token") String token,
            @RequestBody JSONObject params) {
        Result result = new Result();
        if (!tokenService.validate(token)) {
            return result.build(null,Code.D404);
        }
        List<Map<String,String>> list = new ArrayList<>();
        try{
            params.put("args",params.getString("args").replaceAll("=",":"));
            //修改
            deviceModelService.updateDeviceModelArgById(params);
        } catch (Exception e) {
            e.printStackTrace();
            return result.build(null,Code.D400);
        }
        return result.build(null, Code.S212);
    }
}
